package com.lagou.edu.filter;

import com.lagou.edu.remote.UserService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class TokenCheckFilter  implements GlobalFilter, Ordered {

    @Autowired
    private UserService userService;

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().toURL().getPath();
        if (!(path.contains("login") || path.contains("register") || path.contains("code/create"))) {
            List<HttpCookie> tokenList = request.getCookies().get("token");
            String tokenStr = "";
            if(tokenList == null || tokenList.size() == 0){
                response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
                log.debug("=====>未登录！需要重新登陆");
                String data = "login";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
            for (int i = 0; i < tokenList.size(); i++) {
                HttpCookie httpCookie = tokenList.get(i);
                tokenStr = httpCookie.getValue();
                break;
            }
            String email = userService.login(tokenStr);
            if(StringUtils.isEmpty(email)){
                response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
                log.debug("=====>未登录！需要重新登陆");
                String data = "login!";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
